package com.hongdee.insurance.quotation.service.impl;

import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.insurance.dao.ITCrmCarInsuranceDao;
import com.hongdee.insurance.car.entity.TInsuranceCar;
import com.hongdee.insurance.car.service.ITCrmCarWarningConfService;
import com.hongdee.insurance.car.service.ITInsuranceCarService;
import com.hongdee.insurance.order.entity.TInsuranceOrder;
import com.hongdee.insurance.quotation.dao.ITInsuranceQuotationDao;
import com.hongdee.insurance.quotation.entity.TInsuranceQuotation;
import com.hongdee.insurance.quotation.entity.TInsuranceTask;
import com.hongdee.insurance.quotation.service.ITInsuranceQuotationService;
import com.hongdee.insurance.quotation.service.ITInsuranceTaskService;
import com.hongdee.insurance.quotationitem.service.ITInsuranceQuotationItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 王帅
 * @className ${CLASS_NAME}
 * @type
 * @description
 * @path com.hongdee.crm.insurance.service.impl
 * @create 2017/6/26 10:24
 **/
@Service
public class TInsuranceTaskServiceImpl implements ITInsuranceTaskService {

    @Autowired
    private ITInsuranceQuotationDao quotationDao;
    @Autowired
    private ITInsuranceQuotationService quotationService;
    @Autowired
    private ITInsuranceCarService carService;
    @Autowired
    private ITCrmCarWarningConfService warningConfService;
    @Autowired
    private ITInsuranceQuotationItemService quotationItemService;

    /**
     * 获取用户最近的一条保单信息
     * @param vin
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map getLatelyInsurance(String vin, String uid) throws Exception {
        String sql="SELECT * FROM ( SELECT *, " +
                " CASE " +
                " WHEN contractstartinsurance IS NULL THEN compulsory_start_date " +
                " WHEN compulsory_start_date IS NULL THEN contractstartinsurance " +
                " ELSE contractstartinsurance END AS orderDate, " +
                " CASE " +
                " WHEN contractstopinsurance IS NULL THEN compulsory_end_date " +
                " WHEN compulsory_end_date IS NULL THEN contractstopinsurance " +
                " ELSE contractstopinsurance END AS orderEndDate " +
                " FROM t_crm_car_insurance ) t where t.company_id=? and  t.vin=? order by t.orderDate DESC  limit 1" ;
        List<String> params=new ArrayList<>();
        params.add(TokenUtil.getCompanyId(uid));
        params.add(vin);
        return this.quotationDao.info(sql,params.toArray());
    }

    /**
     * 根据车驾号 登录用户ID 获得报价单详情
     * @param vin
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map getLastQuotationInfo(String vin,String uid) throws Exception {
        //1、先查寻通过任务维系报价单信息，取得最后一次的维系保险报价单信息
        Map insuranceTaskInfo=this.getLastInsuranceTask(vin,uid);
        if(insuranceTaskInfo!=null){
            if(insuranceTaskInfo.size()==0){
                return null;
            }else{
                String quotationId= StringUtil.formatEmpty(insuranceTaskInfo.get("quotationId"));
                //2、根据最后一次报价单信息 获取报价单详情
                String sql="select temp.*,ROUND(temp.jqPrice-temp.VVULPT,2) jqNVVUPrice from (  " +
                        " SELECT  " +
                        " q.*, c.insurance_company_name,  " +
                        " case when item.item_price is null THEN '0' ELSE item.item_price END VVULPT,  " +
                        " CASE when q.compulsory_total is null then '0' else q.compulsory_total end jqPrice,  " +
                        " CASE when q.commercialinsurance_total is null then '0' else q.commercialinsurance_total end syPrice " +
                        " FROM  " +
                        " t_insurance_quotation q  " +
                        " left JOIN (select item_price,item_id,quotation_id from t_insurance_quotation_item   " +
                        " where quotation_id=? and item_id='0') item  " +
                        " ON q.id=item.quotation_id  " +
                        " LEFT JOIN t_insurance_company c ON q.insurance_company_id = c.id  " +
                        " WHERE  " +
                        " q.id = ?  " +
                        ")temp";
                //3、返回报价单信息
                List<String> params=new ArrayList<>();
                params.add(quotationId);
                params.add(quotationId);
                Map quotationInfo=this.quotationDao.info(sql,params.toArray());
                return quotationInfo;
            }
        }
        return null;
    }

    /**
     * 最近的更多报价单
     * @param vin
     * @param uid
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String,Object> getLastQuotationMore(String vin,String uid,String companyId,String start,String limit) throws Exception {
        if("".equals(companyId)){
            companyId=TokenUtil.getCompanyId(uid);
        }
        //2、根据最后一次报价单信息 获取报价单详情
        String sql="select temp.*,ROUND(temp.jqPrice-temp.VVULPT,2) jqNVVUPrice from (  " +
                " SELECT  " +
                " q.*, c.insurance_company_name,  " +
                " case when item.item_price is null THEN '0' ELSE item.item_price END VVULPT,  " +
                " CASE when q.compulsory_total is null then '0' else q.compulsory_total end jqPrice,  " +
                " CASE when q.commercialinsurance_total is null then '0' else q.commercialinsurance_total end syPrice "+
                " FROM  " +
                " t_insurance_quotation q  " +
                " left JOIN (select item_price,item_id,quotation_id from t_insurance_quotation_item   " +
                " where item_id='0') item  " +
                " ON q.id=item.quotation_id  " +
                " LEFT JOIN t_insurance_company c ON q.insurance_company_id = c.id  " +
                " WHERE  " +
                " q.company_id=? and q.vin=?  " +
                ")temp order by temp.create_time desc ";
        //3、返回报价单信息
        List<String> params=new ArrayList<>();
        params.add(companyId);
        params.add(vin);
        return this.quotationDao.page(sql.toString(),params.toArray(),start,limit);
    }


    /**
     * 保存报价单信息
     * @param insuranceCar
     * @param quotation
     * @param itemList
     * @param uid
     * @throws Exception
     */
    @Override
    public void saveInsuranceByTask(TInsuranceCar insuranceCar, TInsuranceQuotation quotation,
                                    List<Map<String,Object>> itemList,String uid,String taskId) throws Exception {
        //1、保存车辆信息，先查看车辆信息是否已经存在于客户档案 如不存在，则录入到客户档案表
//        insuranceCar.setId(quotation.getCarId());
        String type=quotationItemService.checkItems(itemList);
        insuranceCar=carService.saveByInsuranceTask(insuranceCar,uid);
        quotation.setIscompulsoryinsurance(type);
        //2、保存报价单信息
        quotation.setCarId(insuranceCar.getId());
        quotation.setVin(insuranceCar.getVin());
        quotation.setPlateNum(insuranceCar.getPlateNum());
        this.saveInsuranceQuotation(quotation,insuranceCar,uid);
        //3、保存保险项目信息
        quotationItemService.saveOrUpdate(itemList,quotation.getId(),uid);
        //4、保存任务与报价单关联关系
        this.saveInsuranceTask(quotation,insuranceCar,uid,taskId);
    }

    /**
     * 保存任务维系保险信息
     * @param quotation
     * @param car
     * @param uid
     * @param taskId
     * @throws Exception
     */
    private void saveInsuranceTask(TInsuranceQuotation quotation,TInsuranceCar car,String uid,String taskId) throws Exception {
        TInsuranceTask tInsuranceTask=quotationDao.insuranceTaskInfo(quotation.getId());

        if(tInsuranceTask==null){
            //说明不存在 需要新增
            tInsuranceTask=new TInsuranceTask();
            tInsuranceTask.setCreateTime(new Date().getTime());
            tInsuranceTask.setCreateUser(uid);
            tInsuranceTask.setCarId(quotation.getCarId());
            tInsuranceTask.setCompanyId(TokenUtil.getCompanyId(uid));
            tInsuranceTask.setQuotationId(quotation.getId());
            tInsuranceTask.setVin(car.getVin());
            tInsuranceTask.setIssue("0");
            tInsuranceTask.setTaskId(taskId);
        }else{
            //说明已存在 修改即可
            tInsuranceTask.setUpdateTime(new Date().getTime());
            tInsuranceTask.setUpdateUser(uid);
        }
        this.quotationDao.saveOrUpdate(tInsuranceTask);
    }


    /**
     * 保存报价单信息
     * @param quotation
     * @param insuranceCar
     * @param uid
     * @throws Exception
     */
    private void saveInsuranceQuotation(TInsuranceQuotation quotation,TInsuranceCar insuranceCar,String uid) throws Exception {
        /**结束时间自动加一年**/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = sdf.parse(quotation.getInsuranceStartDate());
        Long l1=DateUtils.addMonthLongTime(dt.getTime(),+12);
        Long l2=DateUtils.addDayLongTime(l1,-1);
        quotation.setInsuranceStartDate(DateUtils.getTimeStr(quotation.getInsuranceStartDate()));
        quotation.setInsuranceStopDate(sdf.format(l2));
        //判断是否有ID
        if("".equals(StringUtil.formatEmpty(quotation.getId()))){
            //说明为新增
            quotation.setCreateTime(new Date().getTime());
            quotation.setCreateUser(uid);
            //新增判断在同一保险公司是否有时间冲突的报价单
            quotationService.checkQuotationInfo(quotation);
            quotation.setStatus("0");
            quotation.setCompanyId(TokenUtil.getCompanyId(uid));
            this.saveOrUpdateQuotation(quotation,insuranceCar,uid);
        }else{
            TInsuranceQuotation quotationInfo=quotationService.getInfo(quotation.getId());
//            BeanUtils.copyProperties(quotation,quotationInfo);
            quotation.setUpdateTime(new Date().getTime());
            quotation.setUpdateUser(uid);
            quotation.setCreateTime(quotationInfo.getCreateTime());
            quotation.setCreateUser(quotationInfo.getCreateUser());
            quotation.setStatus(quotationInfo.getStatus());
            quotation.setCompanyId(TokenUtil.getCompanyId(uid));
            this.saveOrUpdateQuotation(quotation,insuranceCar,uid);
        }
    }

    private void saveOrUpdateQuotation(TInsuranceQuotation quotation,TInsuranceCar insuranceCar,String uid) throws Exception {
        quotation.setContactPeople(insuranceCar.getContactName());
        quotation.setContactPhone(insuranceCar.getContactPhone());
        quotation.setInsureType("xb");//默认为续保
        //获得车辆信息
        String brand=insuranceCar.getCarBrand();
        String series=insuranceCar.getCarSeries();
        String model=insuranceCar.getCarModel();
        String configure=insuranceCar.getCarConfigure();
        quotation.setPriceWarningType(quotationService.
                checkWarningConf(quotation.getCommercialinsuranceTotal(),uid,brand,series,model,configure));
        this.quotationDao.saveOrUpdate(quotation);
    }





    /**
     * 获得任务维系的最后一条记录
     * @param vin
     * @param uid
     * @return
     * @throws Exception
     */
    private Map getLastInsuranceTask(String vin, String uid) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);
        String sql="select * from ( " +
                " select t.vin,t.quotation_id from (SELECT  vin,quotation_id,company_id,  " +
                " CASE  " +
                " WHEN update_time is null THEN create_time  " +
                " WHEN update_time is not null THEN update_time  " +
                " else create_time END as orderDate  " +
                " FROM  " +
                " T_INSURANCE_TASK) t where t.company_id=? and t.vin=? order by t.orderDate DESC limit 1 " +
                ") t " +
                "UNION ALL " +
                "select * from ( " +
                "select c.vin,q.id quotation_id from t_insurance_quotation q,t_insurance_car c " +
                "where q.car_id=c.id and q.company_id=? and c.vin=? " +
                "order by q.create_time desc limit 1)t2 ";
        List<String> params=new ArrayList<>();
        params.add(companyId);
        params.add(vin);
        params.add(companyId);
        params.add(vin);
        List<Map<String,Object>> list=this.quotationDao.list(sql,params.toArray());
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据报价单ID，更新保险任务回长信息
     * @param car
     * @param order
     * @throws Exception
     */
    @Override
    public void updateTaskInfo(TInsuranceCar car, TInsuranceOrder order) throws Exception {
        //获得任务信息
        String sql="UPDATE t_crm_task_real set `status`='2' where vin=? and type_pcode='bx' and expect_date<=? and  " +
                "company_id=?  ";
        this.quotationDao.executeSQL(sql,car.getVin(),order.getOutOrderDate(),order.getCompanyId());
    }
}
